from flask import Blueprint, request, jsonify
from flask_jwt_extended import get_jwt_identity, jwt_required
from app import db, LogService
from app.models.order_lib import generateOrder, Order
from presenter.order import OrderPresenter
from utils import create_response, StateCode
from utils.server import verifyOrderPayment

order_bp = Blueprint('order', __name__)


@order_bp.route('/orders', methods=['POST'])
@jwt_required()
def createOrder():
    current_user = get_jwt_identity()
    data = request.json
    new_order = generateOrder(data, current_user)
    db.session.add(new_order)
    db.session.commit()
    order_presenter = OrderPresenter(new_order).as_dict()
    LogService.log()
    return jsonify(create_response(StateCode.SUCCESS, data=order_presenter)), 200


@order_bp.route('/orders/<string:order_no>/query_payment', methods=['POST'])
@jwt_required()
def queryPayment(order_no):
    current_user = get_jwt_identity()
    response = verifyOrderPayment(order_no)
    if response.status_code == 200 and response.json().get("data")["state"] == "successful":
        order = Order.setOrderState(order_no, current_user,
                                    state=1, payment_time=response.json().get("data")["pay_time"])
        order_presenter = OrderPresenter(order).as_dict()
        LogService.log()
        return jsonify(create_response(StateCode.SUCCESS, data=order_presenter)), 200
    else:
        LogService.log()
        return jsonify(create_response(StateCode.ORDER_PAY_ERROR)), 400


@order_bp.route('/orders', methods=['GET'])
@jwt_required()
def queryOrder():
    state = request.args.get("state")
    current_user = get_jwt_identity()
    orders = Order.query.filter(Order.passenger_id == current_user, Order.state == state).all()
    order_presenter = [OrderPresenter(order).as_dict() for order in orders]
    LogService.log()
    return jsonify(create_response(StateCode.SUCCESS, data=order_presenter)), 200
